package com.ruoyi.system.websocket;


import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.ruoyi.system.domain.TbDriverCarInfo;
import com.ruoyi.system.service.ITbDriverCarInfoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class WebSocketPaymentService {
    private static final Logger log = LoggerFactory.getLogger(WebSocketPaymentService.class);

    @Autowired
    private ITbDriverCarInfoService driverCarInfoService;


    public void handlePaymentNotification(String message) {
        try {
            JSONObject paymentMessage = JSONUtil.parseObj(message);
            String merchantId = paymentMessage.getStr("merchantId");
            String orderId = paymentMessage.getStr("orderId");
            String amount = paymentMessage.getStr("amount");

            // 根据merchantId查询用户token
            String userToken = getUserTokenByMerchantId(merchantId);
            
            if (userToken != null) {
                // 构建通知消息
                JSONObject notifyMessage = new JSONObject();
                notifyMessage.put("type", "payment");
                notifyMessage.put("orderId", orderId);
                notifyMessage.put("amount", amount);
                notifyMessage.put("audioFile", "/file/"+orderId + ".wav");
                
                // 发送消息给指定用户
                WebSocketServer.sendMessageByToken(userToken, notifyMessage.toString());
                log.info("已发送支付通知给用户, merchantId={}, orderId={}", merchantId, orderId);
            } else {
                log.warn("未找到在线用户, merchantId={}", merchantId);
            }
        } catch (Exception e) {
            log.error("处理支付通知消息失败", e);
        }
    }

    /**
     * 根据商户ID查询用户token
     */
    private String getUserTokenByMerchantId(String merchantId) {
        try {

            TbDriverCarInfo driverInfo = driverCarInfoService.selectDriverInfoByMerchantId(merchantId);
            if (driverInfo != null ) {
              return StpUtil.getTokenValueByLoginId(driverInfo.getId(),"APP");
            }
            
            return null;
        } catch (Exception e) {
            log.error("查询用户token失败, merchantId={}", merchantId, e);
            return null;
        }
    }
} 